import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select
} from 'antd'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import './index.scss'
import { useStore } from '@/store'
import { observer } from 'mobx-react-lite'
import { useEffect, useState } from 'react'
import { http } from '@/utils'
import { useRef } from 'react'
const { Option } = Select

const Publish = () => {
  const { channelStore } = useStore()
  const [imgCount, setImgCount] = useState(1)
  const [fileList, setFileList] = useState([])
  const cacheImgList = useRef()
  const onUpLoadChange = info => {
    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })
    setFileList(fileList)
    cacheImgList.current = fileList
  }
  const onRadioChange = (e) => {
    setImgCount(e.target.value)
    const imgCount = e.target.value
    if (imgCount === 1) {

      const img = cacheImgList.current ? cacheImgList.current[0] : []
      setFileList([img])
    } else if (imgCount === 3) {
      setFileList(cacheImgList.current)
    }
  }
  const onFinish = async (values) => {
    let params = { ...values }
    params.cover = {
      type: values.type,
      images: fileList.map((item) => {
        return item.url
      })
    }
    if (id) {
      // 编辑
      await http.put(`/mp/articles/${id}?draft=false`, params)
    } else {
      // 新增
      await http.post('/mp/articles?draft=false', params)
    }
  }
  const [params] = useSearchParams()
  const id = params.get("id")
  const form = useRef()
  useEffect(() => {
    const loadDetail = async () => {
      const res = await http.get(`/mp/articles/${id}`)
      form.current.setFieldsValue({ ...res.data, type: res.data.cover.type })
      console.log("res=", res)
      setFileList(res.data.cover.images.map(url => {
        return { url }
      }))
      cacheImgList.current = res.data.cover.images.map(url => {
        return { url }
      })
    }
    if (id) {
      loadDetail()
    }
  }, [id])
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? "编辑文章" : "发布文章"}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          ref={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelStore.channelStore.map((item) => {
                return (
                  <Option value={item.name} key={item.id}>{item.name}</Option>
                )
              })}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={onRadioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 &&
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action="http://geek.itheima.net/v1_0/upload"
                fileList={fileList}
                onChange={onUpLoadChange}
                multiple={imgCount > 1 ? true : false}
                maxCount={imgCount}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill theme='snow' className="publish-quill" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {id ? "更新文章" : "发布文章"}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)